package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.system.domain.Project;
import com.ruoyi.system.dto.ProjectFileQueryDTO;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IProjectFileService;
import com.ruoyi.system.service.IProjectAttachmentService;
import com.ruoyi.system.vo.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 项目文件管理服务实现类
 * 
 * @author ruoyi
 * @since 2024-01-01
 */
@Service
public class ProjectFileServiceImpl implements IProjectFileService {

    @Resource
    private ProjectMapper projectMapper;

    @Resource
    private IProjectAttachmentService projectAttachmentService;

    @Override
    public Page<ProjectFileListVO> getProjectFileList(ProjectFileQueryDTO queryDTO) {
        // 1. 获取所有项目（带分页）
        Page<Project> projects = getAllProjects(queryDTO);

        List<Project> records = projects.getRecords();

        // 2. 为每个项目统计文件信息
        List<ProjectFileListVO> result = new ArrayList<>();
        
        for (Project project : records) {
            ProjectFileListVO vo = buildProjectFileListVO(project);
            result.add(vo);
        }
        
        // 3. 应用排序（在内存中排序，因为需要根据文件统计信息排序）
        applySorting(result, queryDTO.getOrderBy(), queryDTO.getOrderDirection());

        // 4. 构建分页结果
        Page<ProjectFileListVO> resultPage = new Page<>(projects.getCurrent(), projects.getSize(), projects.getTotal());
        resultPage.setRecords(result);

        return resultPage;
    }


    /**
     * 获取所有项目（应用搜索条件）
     */
    private Page<Project> getAllProjects(ProjectFileQueryDTO queryDTO) {
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        
        // 项目名称模糊搜索
        if (StringUtils.hasText(queryDTO.getProjectName())) {
            queryWrapper.like(Project::getProjectName, queryDTO.getProjectName());
        }
        
        // 客户名称模糊搜索
        if (StringUtils.hasText(queryDTO.getCustomerName())) {
            queryWrapper.like(Project::getCustomerName, queryDTO.getCustomerName());
        }
        
        // 创建时间范围
        if (queryDTO.getCreateTimeStart() != null) {
            queryWrapper.ge(Project::getCreateTime, queryDTO.getCreateTimeStart());
        }
        if (queryDTO.getCreateTimeEnd() != null) {
            queryWrapper.le(Project::getCreateTime, queryDTO.getCreateTimeEnd());
        }
        
        // 注意：Project类没有isDeleted字段，这里暂时注释掉
        // queryWrapper.eq(Project::getIsDeleted, 0);
        
        // 应用数据库层面的排序（对于项目基本字段）
        applyDatabaseSorting(queryWrapper, queryDTO.getOrderBy(), queryDTO.getOrderDirection());
        
        Page<Project> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());

        return projectMapper.selectPage(page, queryWrapper);
    }

    /**
     * 构建项目文件列表VO
     */
    private ProjectFileListVO buildProjectFileListVO(Project project) {
        ProjectFileListVO vo = new ProjectFileListVO();
        vo.setProjectId(project.getId());
        vo.setProjectName(project.getProjectName());
        vo.setCustomerName(project.getCustomerName());
        vo.setProjectStatus(project.getProgress());
        vo.setProjectStatusName(getProjectStatusName(project.getProgress()));
        
        // 直接使用现有的项目附件管理逻辑获取所有附件
        List<ProjectAttachmentVO> allAttachments = projectAttachmentService.getProjectAttachments(project.getId());
        
        // 统计各类文件数量
        Map<Integer, Integer> fileCountMap = new HashMap<>();
        fileCountMap.put(1, 0); // 设计文件
        fileCountMap.put(2, 0); // 施工文件
        fileCountMap.put(3, 0); // 竣工文件
        fileCountMap.put(4, 0); // 合同
        fileCountMap.put(5, 0); // 其他
        
        String latestFileName = null;
        Integer latestFileType = null;
        LocalDateTime lastUpdateTime = null;
        String lastUpdateBy = null;
        
        // 统计文件数量并找到最新文件
        for (ProjectAttachmentVO attachment : allAttachments) {
            Integer attachmentType = attachment.getAttachmentType();
            if (attachmentType != null && attachmentType >= 1 && attachmentType <= 5) {
                fileCountMap.put(attachmentType, fileCountMap.get(attachmentType) + 1);
            }
            
            // 找到最新的文件
            if (lastUpdateTime == null || 
                (attachment.getCreateTime() != null && attachment.getCreateTime().isAfter(lastUpdateTime))) {
                lastUpdateTime = attachment.getCreateTime();
                lastUpdateBy = attachment.getUploadBy();
                latestFileName = attachment.getOriginalName();
                latestFileType = attachment.getAttachmentType();
            }
        }
        
        // 设置文件数量
        vo.setFileCountMap(fileCountMap);
        vo.setDesignFileCount(fileCountMap.get(1));
        vo.setConstructionFileCount(fileCountMap.get(2));
        vo.setCompletionFileCount(fileCountMap.get(3));
        vo.setContractFileCount(fileCountMap.get(4));
        vo.setOtherFileCount(fileCountMap.get(5));
        vo.setTotalFileCount(fileCountMap.values().stream().mapToInt(Integer::intValue).sum());
        
        // 设置最新文件信息
        vo.setLatestFileName(latestFileName);
        vo.setLatestFileType(latestFileType);
        vo.setLatestFileTypeName(getFileTypeName(latestFileType));
        
        // 设置最后更新信息
        vo.setLastUpdateTime(lastUpdateTime);
        vo.setLastUpdateBy(lastUpdateBy);
        
        return vo;
    }


    /**
     * 应用数据库层面的排序（对于项目基本字段）
     */
    private void applyDatabaseSorting(LambdaQueryWrapper<Project> queryWrapper, String orderBy, String orderDirection) {
        if (!StringUtils.hasText(orderBy)) {
            // 默认按创建时间倒序
            queryWrapper.orderByDesc(Project::getCreateTime);
            return;
        }
        
        boolean isAsc = "asc".equalsIgnoreCase(orderDirection);
        
        switch (orderBy) {
            case "projectName":
                if (isAsc) {
                    queryWrapper.orderByAsc(Project::getProjectName);
                } else {
                    queryWrapper.orderByDesc(Project::getProjectName);
                }
                break;
            case "customerName":
                if (isAsc) {
                    queryWrapper.orderByAsc(Project::getCustomerName);
                } else {
                    queryWrapper.orderByDesc(Project::getCustomerName);
                }
                break;
            case "createTime":
                if (isAsc) {
                    queryWrapper.orderByAsc(Project::getCreateTime);
                } else {
                    queryWrapper.orderByDesc(Project::getCreateTime);
                }
                break;
            default:
                // 对于需要在内存中排序的字段（如fileCount, lastUpdateBy, lastUpdateTime），
                // 先按创建时间排序，后续在内存中重新排序
                queryWrapper.orderByDesc(Project::getCreateTime);
                break;
        }
    }

    /**
     * 应用内存排序（对于需要统计计算的字段）
     */
    private void applySorting(List<ProjectFileListVO> list, String orderBy, String orderDirection) {
        if (!StringUtils.hasText(orderBy)) {
            return;
        }
        
        boolean isAsc = "asc".equalsIgnoreCase(orderDirection);
        
        switch (orderBy) {
            case "fileCount":
                list.sort(isAsc ? 
                    Comparator.comparing(ProjectFileListVO::getTotalFileCount) :
                    Comparator.comparing(ProjectFileListVO::getTotalFileCount).reversed());
                break;
            case "lastUpdateBy":
                list.sort(isAsc ? 
                    Comparator.comparing(ProjectFileListVO::getLastUpdateBy, Comparator.nullsLast(Comparator.naturalOrder())) :
                    Comparator.comparing(ProjectFileListVO::getLastUpdateBy, Comparator.nullsLast(Comparator.naturalOrder())).reversed());
                break;
            case "lastUpdateTime":
                list.sort(isAsc ? 
                    Comparator.comparing(ProjectFileListVO::getLastUpdateTime, Comparator.nullsLast(Comparator.naturalOrder())) :
                    Comparator.comparing(ProjectFileListVO::getLastUpdateTime, Comparator.nullsLast(Comparator.naturalOrder())).reversed());
                break;
            // 对于projectName, customerName, createTime，已经在数据库层面排序，不需要在内存中重新排序
        }
    }


    /**
     * 获取项目状态名称
     */
    private String getProjectStatusName(Integer progress) {
        if (progress == null) {
            return "";
        }
        switch (progress) {
            case 1: return "上门";
            case 2: return "量房";
            case 3: return "设计";
            case 4: return "报价";
            case 5: return "合同";
            case 6: return "施工";
            case 7: return "完工";
            case 8: return "结单";
            default: return "";
        }
    }

    /**
     * 获取文件类型名称
     */
    private String getFileTypeName(Integer fileType) {
        if (fileType == null) {
            return "";
        }
        switch (fileType) {
            case 1: return "设计文件";
            case 2: return "施工文件";
            case 3: return "竣工文件";
            case 4: return "合同";
            case 5: return "其他";
            default: return "";
        }
    }

}
